<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-header">
                <h2>博客管理系统</h2>
                <p>Welcome Back!</p>
            </div>

            <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" :disabled="loading" />
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock"
                        show-password :disabled="loading" />
                </el-form-item>

                <el-form-item>
                    <el-checkbox v-model="rememberMe" :disabled="loading">记住我</el-checkbox>
                    <el-link type="primary" class="forget-pwd">忘记密码？</el-link>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">
                        {{ loading ? '登录中...' : '登录' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup name="Login">
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import request from '../../utils/requestLogin'

const router = useRouter()
const route = useRoute()
const loginFormRef = ref<FormInstance>()
const rememberMe = ref(false)
const loading = ref(false)

// 表单数据
const loginForm = reactive({
    username: '',
    password: '',
})

// 表单验证规则
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
    ]
})

// 登录方法
const handleLogin = () => {
    if (!loginFormRef.value) return

    loginFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                const response = await request.post('http://cylyxsz.w1.luyouxia.net/blog/api/users/login', loginForm)
                localStorage.setItem('token', response.token)
                localStorage.setItem('username', loginForm.username)
                if (rememberMe.value) {
                    localStorage.setItem('rememberedUsername', loginForm.username)
                }

                ElMessage.success('登录成功')

                // 重定向处理
                const redirect = route.query.redirect as string
                router.push(redirect || '/')
            } catch (error) {
                console.error('登录失败:', error)
                ElMessage.error('登录失败，请重试')
            } finally {
                loading.value = false
            }
        }
    })
}

// 检查是否有记住的用户名
const checkRememberedUser = () => {
    const rememberedUsername = localStorage.getItem('rememberedUsername')
    if (rememberedUsername) {
        loginForm.username = rememberedUsername
        rememberMe.value = true
    }
}

// 组件挂载时检查记住的用户名
checkRememberedUser()
</script>

<style scoped>
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 10px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.login-header {
    text-align: center;
    margin-bottom: 40px;
}

.login-header h2 {
    margin: 0;
    color: #333;
    font-size: 28px;
    font-weight: 600;
}

.login-header p {
    margin: 10px 0 0;
    color: #666;
    font-size: 16px;
}

.login-form {
    .el-input {
        --el-input-height: 45px;
    }
}

.forget-pwd {
    float: right;
}

.login-btn {
    width: 100%;
    height: 45px;
    font-size: 16px;
}

:deep(.el-input__wrapper) {
    background-color: #f5f7fa;
    box-shadow: none;
    border: 1px solid #e4e7ed;
}

:deep(.el-input__wrapper:hover) {
    border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 1px #409eff;
}

/* 添加禁用状态样式 */
:deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: #f5f7fa;
    opacity: 0.7;
}

.login-btn.is-loading {
    background-color: #a0cfff;
    border-color: #a0cfff;
    cursor: not-allowed;
}
</style>
